package com.aweqy.hrmanager.controller;

import com.aweqy.hrmanager.dto.LoginRequest;
import com.aweqy.hrmanager.dto.LoginResponse;
import com.aweqy.hrmanager.entity.User;
import com.aweqy.hrmanager.service.UserService;
import com.aweqy.hrmanager.util.JwtUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/auth")
@CrossOrigin
public class AuthController {
    @Autowired
    private UserService userService;
    
    @Autowired
    private JwtUtil jwtUtil;
    
    private final BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();

    @PostMapping("/login")
    public LoginResponse login(@RequestBody LoginRequest loginRequest) {
        LoginResponse response = new LoginResponse();
        
        // 查询用户
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", loginRequest.getUsername());
        User user = userService.getOne(queryWrapper);
        
        if (user != null && passwordEncoder.matches(loginRequest.getPassword(), user.getPasswordHash())) {
            // 生成JWT令牌
            String token = jwtUtil.generateToken(user.getUsername(), user.getRole());
            
            response.setToken(token);
            response.setUsername(user.getUsername());
            response.setRole(user.getRole());
            response.setUserId(user.getUserId());
            response.setMessage("登录成功");
            
            return response;
        } else {
            response.setMessage("用户名或密码错误");
            return response;
        }
    }

    @PostMapping("/logout")
    public Map<String, Object> logout() {
        Map<String, Object> result = new HashMap<>();
        result.put("message", "登出成功");
        return result;
    }

    @GetMapping("/user-info")
    public Map<String, Object> getUserInfo(@RequestHeader("Authorization") String token) {
        Map<String, Object> result = new HashMap<>();
        
        if (token != null && token.startsWith("Bearer ")) {
            String jwtToken = token.substring(7);
            
            if (jwtUtil.validateToken(jwtToken)) {
                String username = jwtUtil.getUsernameFromToken(jwtToken);
                String role = jwtUtil.getRoleFromToken(jwtToken);
                
                result.put("username", username);
                result.put("role", role);
                result.put("message", "获取用户信息成功");
            } else {
                result.put("message", "令牌无效");
            }
        } else {
            result.put("message", "未提供令牌");
        }
        
        return result;
    }
} 